package com.aliyun.messagemgt.application.service.Impl.push.ali;


import com.aliyun.messagemgt.application.service.MsgPushChannel;
import com.aliyun.messagemgt.common.dto.send.*;
import com.aliyun.messagemgt.common.enums.ChannelTypeEnum;
import com.taobao.api.ApiException;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 支付宝小程序 消息推送渠道
 * 2020年5月8日 会议确定需求链路  一码通后端推送--> 消息中心 <--微信小程序拉取
 *
 * @author byp
 * @date 2020/4/29
 */
@Service
public class AliPayPushChannel implements MsgPushChannel {

    @Resource
    private RedisTemplate redisTemplate;

    private static final String ALIPAY = "ALIPAY";

    private static Logger logger = LoggerFactory.getLogger(AliPayPushChannel.class);

    @Override
    public Integer getChannelType() {
        return ChannelTypeEnum.ALIPAY_APPLET.getType();
    }

    @Override
    public void push(PushChannelInfo pushChannelInfo, MsgRecordVO msgRecordVO) throws ApiException {

        List<Receiver> receivers = msgRecordVO.getReceivers();
        if(CollectionUtils.isEmpty(receivers)){
            logger.info("接收人为空");
            return;
        }
        List<MsgBody> contents = msgRecordVO.getContents();
        //针对小程序渠道只接受一人一类型一消息
        Receiver receiver = receivers.get(0);
        MsgBody msgBody = contents.get(0);
        String tag = msgBody.getTag();
        //消息体
        String content = msgBody.getContent();

        String redisKey = ALIPAY + tag + receiver.getReceiverId();
        List<MsgMiddleResult> results = msgRecordVO.getResults();
        try {
            long now = System.currentTimeMillis();
            redisTemplate.opsForZSet().add(redisKey, content, now);

            MsgMiddleResult msgMiddleResult = new MsgMiddleResult().setPushResultCode(1)
                    .setPushResultDescription("支付宝小程序渠道消息推送成功")
                    .setReceivers(msgRecordVO.getReceivers());
            results.add(msgMiddleResult);
        } catch (Exception e) {
            logger.info("支付宝小程序渠道消息推送失败:{}", e.toString());
            MsgMiddleResult msgMiddleResult = new MsgMiddleResult().setPushResultCode(2)
                    .setPushResultDescription("支付宝小程序渠道消息推送失败")
                    .setReceivers(msgRecordVO.getReceivers());
            results.add(msgMiddleResult);
        }

    }

}
